﻿using System.Linq;
using System.Xml.Linq;
using PTop.Application.WeChat;
using PTop.Code;
using PTop.Domain.ViewModel.Wechat;

namespace PTop.Front.Areas.Wechat.Models
{
    public class EventMessage : WechatMsgBase
    {
        public EventMessage()
        {

        }
        public EventMessage(string xml)
        {
            LoadFromXml(xml);
        }


        /// <summary>
        /// 
        /// </summary>
        private static string _template;
        /// <summary>
        /// 模板
        /// </summary>
        public override string Template
        {
            get
            {
                if (string.IsNullOrEmpty(_template))
                {
                    _template = @"<xml>
                                <ToUserName><![CDATA[{0}]]></ToUserName>
                                <FromUserName><![CDATA[{1}]]></FromUserName>
                                <CreateTime>{2}</CreateTime>
                                <MsgType><![CDATA[event]]></MsgType>
                                <Event><![CDATA[{3}]]></Event>
                                <EventKey>{4}</EventKey>
                            </xml>";
                }

                return _template;
            }
        }
        /// <summary>
        /// 事件类型
        /// </summary>
        public string Event { get; set; }
        /// <summary>
        /// 事件KEY值，与自定义菜单接口中KEY值对应
        /// </summary>
        public string EventKey { get; set; }

        public string Ticket { get; set; }

        /// <summary>
        /// 从xml数据加载文本消息
        /// </summary>
        /// <param name="xml"></param>
        public static EventMessage LoadFromXml(string xml)
        {
            EventMessage em = null;
            if (!string.IsNullOrEmpty(xml))
            {
                XElement element = XElement.Parse(xml);
                if (element != null)
                {
                    em = new EventMessage();
                    em.FromUserName = element.Element(WeChatCommon.FROM_USERNAME).Value;
                    em.ToUserName = element.Element(WeChatCommon.TO_USERNAME).Value;
                    em.CreateTime = element.Element(WeChatCommon.CREATE_TIME).Value;
                    em.Event = element.Element(WeChatCommon.EVENT).Value;
                    if (element.Elements(WeChatCommon.EVENT_KEY).Count() > 0)
                    {
                        em.EventKey = element.Element(WeChatCommon.EVENT_KEY).Value;
                    }
                    if (element.Elements(WeChatCommon.TICKET).Count() > 0)
                    {
                        em.Ticket = element.Element(WeChatCommon.TICKET).Value;
                    }
                }
            }

            return em;
        }

        public override string HandleRequest()
        {
            string resContent = "";
            switch (this.Event.ToLower())
            {
                case "subscribe":
                    {
                        //判断是否通过扫描场景二维码
                        if (this.EventKey != null && this.Ticket != null)
                        {
                            //var sceneID = int.Parse(EventKey.Split('_')[1]);
                            //WechatServiceStub stub = new WechatServiceStub();
                            //var ticketObj = stub.GetQRTicket(Ticket, sceneID);
                            ////校验二维码是否存在
                            //if (ticketObj == null)
                            //{
                            //    var msg = new TextMessage()
                            //    {
                            //        Content = "无效的二维码,请刷新二维码后重新扫描",
                            //        CreateTime = WeChatCommon.GetNowTime(),
                            //        FromUserName = this.ToUserName,
                            //        ToUserName = this.FromUserName,
                            //    };
                            //    return msg.GenerateContent();
                            //}
                            ////校验二维码是否已经失效
                            //if (ticketObj.ExpireTime < DateTime.Now)
                            //{
                            //    var msg = new TextMessage()
                            //    {
                            //        Content = "二维码已失效,请刷新二维码并重新扫描",
                            //        CreateTime = WeChatCommon.GetNowTime(),
                            //        FromUserName = this.ToUserName,
                            //        ToUserName = this.FromUserName,
                            //    };
                            //    return msg.GenerateContent();
                            //}
                            //if (string.IsNullOrEmpty(ticketObj.OpenID)) //关联openid到ticket
                            //{
                            //    ticketObj.OpenID = this.FromUserName;
                            //    var result = stub.BindOpenIDToQRTicket(ticketObj);
                            //    if (result.Status == "success")
                            //    {
                            //        resContent = BindTicktSuccess(sceneID, stub, ticketObj);
                            //        return resContent;
                            //    }
                            //    else //关联失败处理
                            //    {
                            //        var msg = new TextMessage()
                            //        {
                            //            Content = "系统故障,请刷新二维码后重新扫描",
                            //            CreateTime = WeChatCommon.GetNowTime(),
                            //            FromUserName = this.ToUserName,
                            //            ToUserName = this.FromUserName,
                            //        };
                            //        resContent = msg.GenerateContent();
                            //        return resContent;
                            //    }
                            //}
                            //else  //ticket已经关联, 判断关联的openid是否与用户的openid是否一致
                            //{
                            //    if (ticketObj.OpenID != this.FromUserName)
                            //    {
                            //        var msg = new TextMessage()
                            //        {
                            //            Content = "此二维码已绑定到另一个用户,请刷新二维码后重新扫描",
                            //            CreateTime = WeChatCommon.GetNowTime(),
                            //            FromUserName = this.ToUserName,
                            //            ToUserName = this.FromUserName,
                            //        };
                            //        return msg.GenerateContent();
                            //    }
                            //}

                            //resContent = BindTicktSuccess(sceneID, stub, ticketObj);
                            //return resContent;
                        }
                        else  //普通关注
                        {
                            var dto = new WxApiApp().GetAndSaveUserInfo(FromUserName);
                            var content = "您好！欢迎您关注" + Configs.GetValue("WeChatSubscription") + "!";
                            if (!string.IsNullOrEmpty(dto.nickname))
                            {
                                content = dto.nickname + "，" + content;
                            }
                            var msg = new TextMessage
                            {
                                Content = content,
                                CreateTime = WeChatCommon.GetNowTime(),
                                FromUserName = this.ToUserName,
                                ToUserName = this.FromUserName,
                            };
                            resContent = msg.GenerateContent();
                        }
                    }
                    break;
                case "scan":
                    {
                        if (this.EventKey != null && this.Ticket != null) //扫描的是带场景的二维码
                        {
                            //根据场景ID获取保存的二维码
                            //var sceneID = int.Parse(this.EventKey);
                            //WechatServiceStub stub = new WechatServiceStub();
                            //var ticketObj = stub.GetQRTicket(this.Ticket, sceneID);
                            ////校验二维码是否已经失效
                            //if (ticketObj.ExpireTime < DateTime.Now)
                            //{
                            //    var msg = new TextMessage()
                            //    {
                            //        Content = "二维码已失效,请刷新二维码并重新扫描",
                            //        CreateTime = WeChatCommon.GetNowTime(),
                            //        FromUserName = this.ToUserName,
                            //        ToUserName = this.FromUserName,
                            //    };
                            //    return msg.GenerateContent();
                            //}

                            ////判断二维码关联的openid是否与用户的openid是否一致,对付用不同手机扫的问题

                            //if (string.IsNullOrEmpty(ticketObj.OpenID))  //将openid与二维码关联绑定
                            //{
                            //    ticketObj.OpenID = this.FromUserName;
                            //    var result = stub.BindOpenIDToQRTicket(ticketObj);
                            //    if (result.Status != "success")
                            //    {
                            //        var msg = new TextMessage()
                            //        {
                            //            Content = "系统故障,请刷新二维码后重新扫描",
                            //            CreateTime = WeChatCommon.GetNowTime(),
                            //            FromUserName = this.ToUserName,
                            //            ToUserName = this.FromUserName,
                            //        };
                            //        return msg.GenerateContent();
                            //    }
                            //}
                            //else if (ticketObj.OpenID != this.FromUserName)
                            //{
                            //    var msg = new TextMessage()
                            //    {
                            //        Content = "此二维码已绑定到另一个用户,请刷新二维码后重新扫描",
                            //        CreateTime = WeChatCommon.GetNowTime(),
                            //        FromUserName = this.ToUserName,
                            //        ToUserName = this.FromUserName,
                            //    };
                            //    return msg.GenerateContent();
                            //}
                            //resContent = BindTicktSuccess(sceneID, stub, ticketObj);
                            //return resContent;
                        }
                    }
                    break;
                case "click":
                    if (EventKey == "contactCustomer")
                    {
                        var msg = new TextMessage()
                        {
                            Content = "欢迎您拨打客服热线：400-630-6888",
                            CreateTime = WeChatCommon.GetNowTime(),
                            FromUserName = this.ToUserName,
                            ToUserName = this.FromUserName,
                        };
                        return msg.GenerateContent();
                    }
                    break;
                default:
                    break;
            }

            return resContent;
        }

        //private string BindTicktSuccess(int sceneID, WechatServiceStub stub, WeChatQRCodeEntity ticketObj)
        //{
        //    //微信传图场景
        //    var sceneType = stub.GetSceneType(sceneID);
        //    var msg = new TextMessage()
        //    {
        //        Content = "success",
        //        CreateTime = WeChatCommon.GetNowTime(),
        //        FromUserName = this.ToUserName,
        //        ToUserName = this.FromUserName,
        //    };
        //    if (sceneType == 1)
        //    {
        //        msg.Content = "Hi,您已开启搜房微信传图模式\n1.点击左下键盘图标\n2.选择右下角+\n3.添加图片\n快速上传手机图片,图片将同步到电脑端,快来尝试吧~";
        //    }
        //    else if (sceneType == 2)//登录场景
        //    {
        //        var bindEntity = stub.GetWeChat_BindEntity(this.FromUserName);
        //        if (bindEntity == null)
        //        {
        //            //引导进入绑定界面
        //            var url = string.Format("http://b.agent.fang.com/wapagent/myaccount?openid={0}&sceneID={1}&ticket={2}", this.FromUserName, sceneID, ticketObj.Ticket);
        //            msg.Content = "此微信号尚未与搜房帮帐号绑定,绑定后可以使用微信登录功能<a href='" + url + "'>去绑定</a>";
        //        }
        //        else //帐号与微信号已经绑定
        //        {
        //            var url = string.Format("http://b.agent.fang.com/wapagent/login/signin/WeChatConfirmLogin?sceneid={0}&ticket={1}&openid={2}", sceneID.ToString(), ticketObj.Ticket, this.FromUserName);
        //            msg.Content = "<a href='" + url + "'>点此登录</a>";
        //        }
        //    }

        //    return msg.GenerateContent();
        //}

        public override string MsgType
        {
            get { return "event"; }
        }
    }
}